package com.kugou.internal.service;

import com.kugou.internal.MiscUtils;
import com.kugou.internal.SpyHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * Created by Alex on 2014/9/23
 */

@Component
public class SpyService {

    @Autowired
    private SpyHelper spyHelper;

    public String doSpy(String code, String username, String password, String mainClass) {
        if (MiscUtils.isEmpty(code) || MiscUtils.isEmpty(username)
                || MiscUtils.isEmpty(password) || MiscUtils.isEmpty(mainClass)) {
            return "参数错误！";
        }
        boolean checkSuccess = SpyHelper.checkAuth(username, password);
        if (!checkSuccess) {
            return "auth fail!";
        }
        StringBuilder sb = new StringBuilder();
        try {
            Object o = spyHelper.codeToObject(code, mainClass);
            Method method = o.getClass().getDeclaredMethod("spy");
            method.invoke(o);
            Field field = o.getClass().getDeclaredField("sb");
            field.setAccessible(true);
            sb = (StringBuilder) field.get(o);
            return sb.toString();
        } catch (Exception e) {
            String stackTrace = MiscUtils.getStackTrace(e);
            sb.append(stackTrace);
        }
        if (sb.length() <= 0) {
            return "Unknown Error";
        } else {
            return sb.toString();
        }
    }
}

